<template>
	<view class="savepadding">

		<view style="position: relative;">

			<view class="tab-select" :style="{ opacity: afterHeaderOpacity, }">
				<view class="tab-select-item" :class="{'tab-select-active':tabIndex === tabSelect}"
					v-for="(tabItem, tabIndex) in dataDetail.introduceList" :key="tabIndex" @click="tabClick(tabIndex)">
					{{tabItem.introduceName}}
				</view>
			</view>


			<u-swiper :list="dataDetail.carModelUrlList" height="240" radius="0" @change="e => current = e.current"
				autoplay>

				<!-- v-if="dataDetail.carModelUrlList && dataDetail.carModelUrlList.length>0" -->

				<view slot="indicator" class="indicator">
					<view class="indicator__dot" v-for="(item, index) in dataDetail.carModelUrlList" :key="index"
						:class="[index === current && 'indicator__dot--active']">
					</view>
				</view>

			</u-swiper>

			<view class="color-wrap">

				<view class="color-list" v-if="colorList.length>0">
					<view v-for="(colorItem, colorindex) in colorList" :key="colorindex" class="color-bg"
						:style="{'background-color':colorItem.color}"
						:class="{'color-active':selectColorIndex === colorindex}"
						@click="selectColorIndex = colorindex">
					</view>
				</view>

				<!-- <text class="color-text">颜色:{{colorList[selectColorIndex].name}}</text> -->

				<text class="color-text" v-if="dataDetail.carModelColor">颜色:{{dataDetail.carModelColor}}</text>

			</view>

			<image v-if="dataDetail.videoUrl"
				style="width: 80upx;height: 80upx;position: absolute;left: 60upx;bottom: 37upx;" :src="videoPlayImg"
				mode="scaleToFill" @click="playvideo"></image>
		</view>

		<view class="item base-info">
			<view class="base-info-top">

				<view class="base-info-top-model">
					<text
						class="base-info-top-model-brand">{{filterNull(dataDetail.brandName)+" "+filterNull(dataDetail.seriesName)}}</text>
					<text class="base-info-top-model-series">{{filterNull(dataDetail.modelName)}}</text>
				</view>

				<text class="base-info-top-param" @click="goParam">参数配置</text>
			</view>

			<view class="base-info-tags" v-if="dataDetail.tagNames && dataDetail.tagNames.length>0">
				<text v-for="(item, index) in strSplit(dataDetail.tagNames)" :key="item">
					{{item}}
				</text>
			</view>

			<text class="base-info-price" v-if="bizType==6">市场指导价：¥{{filterNull(dataDetail.guidePrice)}}万/起</text>
			<text class="base-info-price"
				v-else-if="dataDetail.schemeType==1">市场指导价：¥{{filterNull(dataDetail.guidePrice)}}万/起</text>
			<view v-else>
				<text class="base-info-price">
					{{dataDetail.schemeType==2?"整备费":dataDetail.schemeType==4?"首付":"保证金"}}：¥{{filterNull(dataDetail.busAmount)}}元/起
				</text>
				<text class="base-info-price"
					style="margin-left: 30upx;">月租金：¥{{filterNull(dataDetail.monthlyRent)}}元/起</text>
			</view>


		</view>

		<view class="item base-info" style="border-radius: 16upx;" v-if="dataDetail.carModelRemark">
			<text style="font-size: 28upx;
					color: $black33;
					font-weight: bold;">
				费用说明</text>

			<text style="font-size: 22upx;color: #999999;margin-top: 20upx;">说明：{{dataDetail.carModelRemark}}</text>
		</view>


		<view v-for="(tItem, tIndex) in dataDetail.introduceList" :key="tIndex" :id="tItem.sort">
			<rich-text :nodes="tItem.introduceValue"></rich-text>
		</view>

		<view style="height:130upx"></view>
		<!-- 试驾 -->
		<!-- <view class="bottom savepadding" v-if="bizType == 6"> -->
		<view class="bottom savepadding">

			<button style="position: absolute;width: 260upx;height: 96upx;opacity: 0;" open-type='share'></button>
			<text class="bottom-share">分享好友</text>

			<!-- <button class="bottom-share" open-type='share'>分享好友</button> -->
			<!-- <text class="bottom-share">分享好友</text> -->
			<text class="bottom-testdrive"
				@click="goAddOrder">{{bizType == 6?'立即试驾':1 == dataDetail.schemeType?'申请购车':'去下单'}}</text>
			<text class="bottom-testdrive" @click="goAskPrice">询问价格</text>
		</view>
		<!-- 直购 -->
		<!-- <view class="bottom savepadding" v-else-if="1 == dataDetail.schemeType">
            <button style="position: absolute;width: 375upx;height: 96upx;opacity: 0;" open-type='share'></button>
            <text class="bottom-share">分享好友</text>
            <text class="bottom-testdrive" @click="goAddOrder">申请购车</text>
        </view> -->
		<!-- 其他 -->
		<!-- <view class="bottom2 savepadding" v-else @click="goAddOrder">
            去下单
        </view> -->

		<u-popup :safeAreaInsetBottom="true" mode="center" :show="showVideo" overlay :customStyle="{width:'100%'}"
			closeOnClickOverlay @close="close">

			<video id="myVideo" :src="dataDetail.videoUrl" controls style="width: 100%;"></video>
		</u-popup>
		<!-- 登录弹窗 -->
		<LoginMask></LoginMask>
	</view>
</template>

<script>
	import isEmpty from 'lodash/isEmpty';
	import LoginMask from '@/components/layout/login-mask.vue';
	import {
		schemeinfo
	} from '../../../common/api.js';
	import moment from '@/util/moment.js'

	export default {
		components: {
			LoginMask,
		},
		data() {
			return {
				// bannerList: [
				// {
				// 	url: 'https://cdn.uviewui.com/uview/resources/video.mp4',
				// 	title: '昨夜星辰昨夜风，画楼西畔桂堂东',
				// 	poster: 'https://cdn.uviewui.com/uview/swiper/swiper1.png'
				// },
				// {
				// 	url: 'https://cdn.uviewui.com/uview/swiper/swiper2.png',
				// 	title: '身无彩凤双飞翼，心有灵犀一点通'
				// },
				// {
				// 	url: 'https://cdn.uviewui.com/uview/swiper/swiper3.png',
				// 	title: '谁念西风独自凉，萧萧黄叶闭疏窗，沉思往事立残阳'
				// }
				// ],
				colorList: [
					// {
					// 	name: '极地白',
					// 	color: '#fff'
					// },
					// {
					// 	name: '热情红',
					// 	color: '#f00'
					// },
					// {
					// 	name: '草原绿',
					// 	color: '#22ff30'
					// },
				],
				// tags: ["新能源", "很好用", "六的一批", "六的一批", "六的一批", "六的一批", "六的一批", "六的一批", "六的一批"],
				current: 0,
				selectColorIndex: 0,
				tabSelect: 0,
				schemeId: '',
				showVideo: false,
				videoContext: null,
				videoPlayImg: this.baseImageUrl + "uni_rental/playvideo.png",
				bizType: 0, //1.热门租车 2.以租代购 3.长租 4.金融分期 5.直购 6.试驾 7.选车
				dataDetail: {

				},
				afterHeaderOpacity: 0, //不透明度
			}
		},
		computed: {
			openid() {
				return this.$store.state.user.openid;
			},
			isNotLogin() {
				return uni.$u.test.isEmpty(this.$store.state.user.userInfo);
			},
			deptId() {
				return this.$store.state.user.deptId;
			},
		},
		onReady() {
			// this.calcAnchor();//计算锚点高度，页面数据是ajax加载时，请把此行放在数据渲染完成事件中执行以保证高度计算正确
		},
		onPageScroll(e) {

			//锚点切换
			let allLength = this.dataDetail.introduceList.length;
			for (let index in this.dataDetail.introduceList) {
				let rindex = allLength - index - 1;

				let anchor = this.dataDetail.introduceList[rindex];

				if (e.scrollTop >= anchor.top) {
					// console.log('e的比较', e.scrollTop+'=='+anchor.top);
					this.tabSelect = rindex;
					return
				}
			}



			//导航栏渐变
			let tmpY = 375;
			e.scrollTop = e.scrollTop > tmpY ? 375 : e.scrollTop;
			this.afterHeaderOpacity = e.scrollTop * (2 / tmpY);
			// console.log('e的滑动', e.scrollTop);


		},

		methods: {
			getData() {
				schemeinfo({
					params: {
						schemeId: this.schemeId,
						longitude: '',
						latitude: '',
						deptId: this.deptId
					}
				}).then(res => {
					this.dataDetail = res;
					console.log('之前', this.dataDetail.carModelUrlList);

					if (!uni.$u.test.isEmpty(this.dataDetail.carModelUrlList)) {
						this.dataDetail.carModelUrlList = this.dataDetail.carModelUrlList.map(item => this
							.baseImageUrl + item);
					}
					if (!uni.$u.test.isEmpty(this.dataDetail.videoUrl)) {
						this.dataDetail.videoUrl = this.baseImageUrl + this.dataDetail.videoUrl;
					}

					this.dataDetail.introduceList = this.dataDetail.introduceList.map(item => {

						item.sort = 'a' + item.sort;

						return item;
					})
					
					
					//如果门店id是空，从详情获取使用门店第一个
					if (uni.$u.test.isEmpty(this.deptId)) {
						getApp().globalData.tempDeptId = this.dataDetail.deptEntities[0].deptId;
						this.$store.commit('user/saveSourceType', 2);
						this.$store.commit('user/savedeptId', this.dataDetail.deptEntities[0].deptId);
					
						this.$store.dispatch('app/getStoreInfo', this.dataDetail.deptEntities[0].deptId);
					}
					
					

					console.log('之后', this.dataDetail.carModelUrlList);

					// this.$nextTick(()=>{
					// 	this.calcAnchor();//计算锚点高度，页面数据是ajax加载时，请把此行放在数据渲染完成事件中执行以保证高度计算正确
					// })

					setTimeout(() => {
						this.calcAnchor(); //计算锚点高度，页面数据是ajax加载时，请把此行放在数据渲染完成事件中执行以保证高度计算正确
					}, 1000)

				})
			},

			//跳转锚点
			tabClick(index) {
				this.afterHeaderOpacity = 1;
				uni.pageScrollTo({
					scrollTop: this.dataDetail.introduceList[index].top,
					duration: 0
				});
				setTimeout(() => {
					this.tabSelect = index;
				}, 50)
			},
			//计算锚点高度
			calcAnchor() {

				for (let index in this.dataDetail.introduceList) {

					let anchor = this.dataDetail.introduceList[index];

					let commentsView = uni.createSelectorQuery().select("#" + anchor.sort);

					commentsView.boundingClientRect((data) => {
						let statusbarHeight = 0;
						//APP内还要计算状态栏高度
						// #ifdef APP-PLUS
						statusbarHeight = plus.navigator.getStatusbarHeight()
						// #endif
						let headerHeight = uni.upx2px(100);

						let topHeight = statusbarHeight + headerHeight;
						// anchor.top = Math.ceil(data.top - topHeight);
						anchor.top = data.top - topHeight;

					}).exec();
				}

			},

			strSplit(str) {
				if (str !== '' && str != undefined) {
					return str.split(',')
				} else {
					return []
				}
			},

			async goAddOrderHandle(path) {
				// 拼接跳转地址
				const url = path +
					"?brandName=" + this.dataDetail.brandName + // 品牌名称
					"&seriesName=" + this.dataDetail.seriesName + // 车系名称
					"&modelName=" + this.dataDetail.modelName + // 车型名称
					"&modelId=" + this.dataDetail.modelId + // 车型id
					"&schemeId=" + this.schemeId + // 方案id
					"&schemeType=" + this.dataDetail.schemeType + // 方案类型(1.直购，2分期购车，3租赁 4.金融分期)
					"&schemeTypeStr=" + this.dataDetail.schemeTypeStr // 方案类型名称 


				if (6 == this.bizType) {
					//试驾
					console.log('试驾直接跳转');
					uni.navigateTo({
						url
					});
				} else {
					if (1 == this.dataDetail.schemeType) {
						//直购
						console.log('直购直接跳转');
						uni.navigateTo({
							url
						});
					} else {
						//其他
						console.log('其他跳转认证');

						if (url.indexOf('ask-price') > -1) {
							//询问价格不需要认证，直接跳转
							uni.navigateTo({
								url
							});
						} else {
							// 验证实名
							const verifyRelaName = await this.$store.dispatch('app/verifyRelaName', {
								openid: this.openid, // openid
								redirect: url, // 跳转地址
							});
							// 已实名的话直接跳转
							if (verifyRelaName) {
								uni.navigateTo({
									url
								});
							}
						}


					}
				}

			},

			async goAddOrder() {
				if (this.isNotLogin) {
					await this.$store.dispatch('user/MmvLogin'); // 获取openid
					return;
				}
				if (6 == this.bizType) {
					//试驾
					this.goAddOrderHandle('/pages/testDrive/experience-now');
				} else {
					if (1 == this.dataDetail.schemeType) {
						//直购
						this.goAddOrderHandle('/pages/car/buy');
					} else {
						//其他
						this.goAddOrderHandle('/pages/schemeSelection/schemeSelection');
					}
				}
			},
			// 询问价格
			async goAskPrice() {
				if (this.isNotLogin) {
					await this.$store.dispatch('user/MmvLogin'); // 获取openid
					return;
				}
				// 询问价格
				this.goAddOrderHandle('/pages/testDrive/ask-price');
			},

			goParam() {
				uni.navigateTo({
					url: '../../testDrive/parameter-configuration?modelId=' + this.dataDetail.modelId
				})
			},

			playvideo() {
				this.showVideo = true;
				console.log('播放', this.videoContext);
				this.videoContext.play();
			},

			close() {
				console.log('关闭了');
				this.showVideo = false;
			},

			onShareAppMessage(res) {
				this.$store.dispatch('home/recordShare')

				return {
					path: '/pages/car/cardetail/cardetail?bizType=' + this.bizType + '&schemeId=' + this.schemeId +
						'&deptId=' + this.$store.state.user.deptId + '&customerId=' + this.$store.state.user.userInfo
						.customerId
				}
			}

		},
		onShareTimeline() {
			this.$store.dispatch('home/recordShare')

			return {
				path: '/pages/car/cardetail/cardetail?bizType=' + this.bizType + '&schemeId=' + this.schemeId +
					'&deptId=' + this.$store.state.user.deptId + '&customerId=' + this.$store.state.user.userInfo
					.customerId
			}
		},
		onLoad(op) {

			//记录开始时间
			getApp().globalData.taskStartTime = new Date().getTime();

			// console.log('开始时间', moment(getApp().globalData.taskStartTime).format('YYYY-MM-DD HH:mm:ss'));

			getApp().globalData.objType = 8;


			if (!uni.$u.test.isEmpty(op.scene)) {
				const scene = decodeURIComponent(op.scene);
				let s_list = scene.split('=');
				console.log('op-scene=>', s_list);

				//（任务id=推广人id=推广人类型=推广方案id=方案类型1.直购，2分期购车，3租赁 4.金融分期）
				getApp().globalData.taskObjId = s_list[0];
				getApp().globalData.personnelId = s_list[1];
				getApp().globalData.personnelType = s_list[2];
				op.schemeId = s_list[3];
				op.bizType = s_list[4];
			}

			this.bizType = op.bizType;
			this.schemeId = op.schemeId;

			getApp().globalData.objId = this.schemeId;


			//这里deptId可能没有，扫管理端二维码就没有，从详情接口获取
			getApp().globalData.tempDeptId = op.deptId;
			if (!uni.$u.test.isEmpty(op.deptId)) {
				this.$store.commit('user/saveSourceType', 4);
				this.$store.commit('user/savedeptId', op.deptId);

				this.$store.dispatch('app/getStoreInfo', op.deptId);
			}

			getApp().globalData.tempCustomerId = op.customerId;
			if (!uni.$u.test.isEmpty(op.customerId)) {
				this.$store.commit('user/saveCustomerId', op.customerId);
			}


			this.getData();

			this.videoContext = uni.createVideoContext('myVideo');
			
			
			if(uni.$u.test.isEmpty(this.openid)){
				//如果openid是空，可能是从扫码直接进入的，得等openid那个接口请求完了收到通知，再调操作记录接口
				uni.$on('getOpenIded', res=>{
					console.log('我收到openid了');
					
					//访客
					this.$store.dispatch('home/recordUse', {
						recordType: 2,
					})
				})
			}else{
				//访客
				this.$store.dispatch('home/recordUse', {
					recordType: 2,
				})
			}
			
		},
		onUnload() {

			let nowTimes = new Date().getTime();

			let duration = Math.round((nowTimes - getApp().globalData.taskStartTime) / 1000);


			//访问
			this.$store.dispatch('home/recordUse', {
				recordType: 3,
				objRecordData: {
					durationTime: duration,
					recordTime: moment(nowTimes).format('YYYY-MM-DD HH:mm:ss')
				}
			})
		}
	}
</script>

<style lang="scss" scoped>
	.indicator {
		@include flex(row);
		justify-content: center;
		margin-bottom: 60upx;

		&__dot {
			height: 12upx;
			width: 12upx;
			border-radius: 100upx;
			background-color: rgba(255, 255, 255, 0.35);
			margin: 0 7upx;
			transition: background-color 0.3s;

			&--active {
				background-color: $green12;
			}
		}
	}

	.color-wrap {
		@include flex(column);
		align-items: center;
		position: absolute;
		right: 63upx;
		bottom: 35upx;

		.color-text {
			font-size: 24upx;
			color: #232323;
			margin-top: 12upx;
			text-shadow: #fff 2upx 2upx 6upx;
		}

		.color-list {
			@include flex;
			align-items: center;
			background-color: #e2e2e2;
			border-radius: 90upx;
			height: 45upx;

			.color-bg {
				width: 26upx;
				height: 26upx;
				margin: 0 9upx;
				border-radius: 100upx;
			}

			.color-active {
				width: 36upx;
				height: 36upx;
			}
		}
	}

	.base-info {
		@include flex(column);
		margin: 28upx 35upx;
		padding: 30upx 38upx 30upx 36upx;
		border-radius: 16upx;

		&-top {
			@include flex;
			justify-content: space-between;

			&-model {
				@include flex(column);

				&-brand {
					font-size: 28upx;
					color: $black33;
					font-weight: bold;
				}

				&-series {
					font-size: 20upx;
					color: $black99;
					margin-top: 3upx;
				}
			}

			&-param {
				width: 140upx;
				height: 47upx;
				line-height: 47upx;
				text-align: center;
				color: $green12;
				font-size: 24upx;
				border-radius: 2upx;
				border: 1upx #bebebe solid;
			}
		}

		&-tags {
			display: inline-flex;
			flex-wrap: wrap;
			margin-top: 18upx;

			text {
				@include flex;
				height: 43upx;
				align-items: center;
				flex-wrap: wrap;
				margin: 10upx 10upx 0 0;
				padding: 0 14upx;
				border-radius: 6upx;
				background-color: $green12;
				font-size: 20upx;
				color: $white;
			}
		}

		&-price {
			margin-top: 18upx;
			color: $redec;
			font-size: 22upx;
			font-weight: bold;
		}
	}

	// <view class="tab-select">
	// 	<view class="tab-select-item" :class="{'tab-select-active':tabIndex === tabSelect}" v-for="(tabItem, tabIndex) in dataDetail.introduceList" :key="tabIndex" @click="tabClick(tabIndex)">
	// 		<text>{{tabItem.introduceName}}</text>
	// 	</view>
	// </view>

	.tab-select {
		@include flex;
		justify-content: space-evenly;
		height: 80upx;
		font-weight: bold;
		font-size: 28upx;
		background-color: white;
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 1;

		&-item {
			width: 0;
			flex-grow: 1;
			color: $black13;

			line-height: 80upx;
			text-align: center;
		}

		&-active {
			color: #F83C57;
		}
	}

	.bottom {
		width: 100%;
		position: fixed;
		bottom: 0;
		z-index: 2;
		@include flex;
		background-color: $white;

		&-share {
			line-height: 96upx;
			flex-grow: 1;
			text-align: center;
			font-size: 32upx;
			color: $black66;
			background-color: $white;
			margin: 0px;
			padding: 0px;
			/*自定义边框*/
			border: 0px;
			/*消除默认点击蓝色边框效果*/
			outline: none;
		}

		&-testdrive {
			line-height: 96upx;
			flex-grow: 1;
			text-align: center;
			font-size: 32upx;
			color: $white;
			background-color: $redec;
		}
	}

	.bottom2 {
		width: 100%;
		height: 96upx;
		text-align: center;
		line-height: 96upx;
		position: fixed;
		font-size: 32upx;
		color: $white;
		bottom: 0;
		z-index: 2;
		background-color: $redec;
	}
</style>
